﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HalconDotNet;
using MachineVision.Core.TemplateMatch.Shared;

namespace MachineVision.Core.Extensions
{
    public static class HObjectExtensions
    {
        /// <summary>
        ///  该扩展方法用于判断是否设定检测区域，
        ///  如果参数有效则返回需要裁剪的区域，
        ///  否则返回本身
        /// </summary>
        /// <param name="image">原图</param>
        /// <param name="row1">row1</param>
        /// <param name="col1">col1</param>
        /// <param name="row2">row2</param>
        /// <param name="col2">col2</param>
        /// <returns>截取后图像</returns>
        public static HObject ReduceDomain(this HObject image, ROIParameter roi = null)
        {
            if (roi != null)
            {
                if (!(roi.Row1 == default(HTuple)
                && roi.Column1 == default(HTuple)
                && roi.Row2 == default(HTuple)
                && roi.Column2 == default(HTuple)))
                {
                    //生成矩形检测区
                    HOperatorSet.GenRectangle1(out HObject rectangle, roi.Row1, roi.Column1, roi.Row2, roi.Column2);
                    //截取检测区图像
                    HOperatorSet.ReduceDomain(image, rectangle, out HObject imageReduced);
                    return imageReduced;
                }
            }
            return image;
        }
        /// <summary>
        /// 彩色图转灰度图
        /// </summary>
        /// <param name="image"></param>
        /// <returns></returns>
        public static HObject Rgb1ToGray(this HObject image)
        {
            HOperatorSet.Rgb1ToGray(image, out HObject grayImage);
            return grayImage;
        }
        /// <summary>
        /// crop_domain能够对图像的尺寸进行剪裁，即新图像ImagePart尺寸变小
        /// </summary>
        /// <param name="image"></param>
        /// <returns></returns>
        public static HObject CropDomain(this HObject image)
        {
            HOperatorSet.CropDomain(image, out HObject imagePart);
            return imagePart;
        }

        public static void SaveImage(this HObject image, string filename)
        {
            if (image != null)
            {
                if (string.IsNullOrEmpty(filename))
                {

                    HOperatorSet.WriteImage(image, "bmp", 0, filename);
                    return;
                }
            }
            throw new ArgumentNullException("参数不可为空");
        }
    }
}
